<template>
  <div>
    <div style="position: fixed;background-color: #ececec;width: 100%;height: 100%;top: 0;left: 0;overflow: auto">
      <div style="position: fixed;background-color: white;width: 100%;height: 75px;border-radius: 2%;z-index: 999">
        <img
            src="https://img.bosszhipin.com/beijin/mcs/chatphoto/20180821/ed16e2b9dbffaed80e229acf3c8ddbdfcfcd208495d565ef66e7dff9f98764da.jpg?x-oss-process=image/resize,w_140,limit_0/format,webp"
            width="70px" height="70px" style="margin-left: 350px;margin-top: 5px">
        <p style="color: #0ca453;font-weight: bold;font-size: 16px;position: fixed;top: 20px;left: 460px;">
          树叶招聘旗下<br>职场社区</p>
        <img src="../assets/shuxian.png" width="40" height="40" style="position: fixed;top: 20px;left: 415px;">
        <div class="search-container" style="position: fixed;top: 24px;left: 600px;">
          <input type="text" class="search-box" placeholder="搜一搜感兴趣的问题/动态/话题" v-model="ReserchInput">
        </div>
        <img src="../assets/fangfajing.png" width="30" height="30" style="position: fixed;top: 26px;left: 860px;"
             @click="search(this.ReserchInput)">
        <img src="../assets/post.png" width="17" height="17"
             style="position: fixed;top: 34px;left: 1015px;z-index: 999">
        <el-button type="success" style="position: fixed;top: 26px;left:950px" @click="publish">发动态&ensp;&ensp;
        </el-button>
      </div>
      <div>
        <UserMenu style="margin-top: 20px" />
      </div>
      <div style="background-color: white;height: 260px;width: 340px;position: absolute;margin: 100px 360px">
        <img src="../assets/edit.png" width="25" height="25" style="margin: 20px 300px" @click="edit()">
        <el-image
            style="width: 110px;height: 110px;border-radius: 50%;margin: 10px 110px;"
            :src=this.user.image
        />
        <span style="font-weight: bold;margin: 10px 120px">{{this.user.sickname}}</span>

      </div>
      <div>
        <a-modal
            v-model:visible="dialogComment"
            :footer="null"
            width="700px"
            @cancel="cancelComment()"
        >
          <template #title>
            <div style="text-align: center;">{{this.commentNum}}条评论</div>
          </template>

          <!-- 评论列表容器 -->
          <div style="height: 600px; width: 675px;;overflow-y: auto">
            <div
                v-for="items in commentmessage"
                style="display: flex; position:relative; width: 600px; height: 140px; border-bottom: 1px solid black; padding-bottom: 10px;">

              <el-image style="width: 45px; margin: 15px; height: 45px; border-radius: 50%" :src="items.image" fit="fill"></el-image>

              <div style="position: absolute; margin-top:70px; margin-left: 15px">
                <span style="font-size: 14px"><span v-if="items.replysickname !== null">回复&ensp;{{items.replysickname}}&ensp;:</span>{{ items.replycontent }}</span>
              </div>

              <div style="position: absolute; margin-left: 75px; margin-top: 25px">
                <p style="font-size: 14px;">{{ items.sickname }}</p>
              </div>

              <div>
                <p style="font-size: 12px; opacity: 50%; position: absolute; top: 100px; left: 15px">{{ items.replytime }}</p>
              </div>
              <button class="text-button" style="margin-left: 470px;margin-top: 100px;opacity: 50%" @click="replyPl(items.id,items.sickname)">
                <img src="../assets/response.png" width="25" height="25">回复
              </button>
            </div>
          </div>

          <a-textarea
              style="width: 570px"
              v-model:value="textareaComment"
              :placeholder=this.inputComment
              auto-size
          />
          <a-button type="primary" @click="sendComment()" style="margin-top: 20px">发布</a-button>
        </a-modal>
      </div>
      <div style="background-color: white;height: 60px;width: 600px;position: absolute;margin: 100px 720px">
        <el-check-tag checked style="margin: 15px">全部动态</el-check-tag>
      </div>
      <div v-for="item in message" style="display: flex;position:relative;top:160px;left:720px;margin-top: 20px;width: 600px;height: auto;background-color:white;border-radius: 1%">
        <el-image style="width: 45px;margin: 15px;height: 45px;border-radius: 50%" :src="item.image" fit="fill"></el-image>
        <div style="margin-top:75px;margin-left:-60px;">
          <p style="font-size: 14px;word-wrap: break-word; overflow-wrap: break-word;width: 550px;">{{ item.content }}</p>
          <el-image style="width: 110px;height: 80px;margin-top:10px;border-radius: 8%" :src="item.commentimage"
                    fit="fill"></el-image>
          <br>
          <button class="text-button" style="margin-top: 10px;" @click="giveLike(item.foreignid)">
            <el-icon><Pointer/></el-icon>&ensp;{{ item.likenum }}赞
          </button>
          <button class="text-button" style="margin-left: 25px" @click="comment(item.foreignid)">
            <el-icon><DocumentCopy/></el-icon>&ensp;评论
          </button>
          <button class="text-button" style="margin-left: 25px" @click="Delete(item.foreignid)" v-if="user.sickname === item.sickname">
            <el-icon><Delete /></el-icon>&ensp;删除
          </button>
        </div>
        <div style="position: absolute;margin-left: 75px;margin-top: 25px">
          <p style="font-size: 14px;">{{ item.sickname }}</p>
        </div>
        <div>
          <p style="font-size: 12px;opacity: 50%;position: absolute;top: 27px;left: 500px">{{ item.posttime }}</p>
        </div>
      </div>
      <div>
        <el-dialog
            v-model="dialogVisible"
            title="发布动态"
            width="750"
        >
          <el-image class="dropbtn" style="width: 50px; height: 50px;" :src="this.user.image" fit="fill"/>
          <el-input
              v-model="textarea"
              maxlength="1000"
              style="width: 640px;margin-left: 25px"
              placeholder="有什么想说的通通倒进这里..."
              show-word-limit
              type="textarea"
          />
          <div style="position: relative;top: 38px;left:70px">
            <el-upload
                ref="upload"
                action="http://localhost:9090/file/upload"
                list-type="picture-card"
                :auto-upload="false"
                :file-list="fileList"
                :on-success="handleSuccess"
            >
              <el-icon>
                <Plus/>
              </el-icon>
              <template #file="{ file }">
                <div>
                  <img class="el-upload-list__item-thumbnail" :src="file.url"/>
                  <span class="el-upload-list__item-actions"><span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)"><el-icon><Delete/></el-icon></span></span>
                </div>
              </template>
            </el-upload>
          </div>
          <div style="position: relative;left: 650px;"><el-button type="primary" @click="send()">发布</el-button></div>
        </el-dialog>
      </div>
      <div>
        <el-dialog
            v-model="EditMsgdialogVisible"
            title="编辑个人资料"
            width="550"
        >
          <el-check-tag checked style="margin-left: 450px" @click="achieve()">完成</el-check-tag>
          <el-image class="dropbtn" style="width: 100px; height: 100px;margin: 10px 200px" :src="this.user.image" fit="fill"/>
          <p style="margin: 2px 240px">昵称</p>
          <el-input v-model="sicknameinput" style="width: 240px;margin-left: 140px"  />
        </el-dialog>
      </div>
    </div>
  </div>

</template>

<style scoped>
.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-box {
  padding: 10px;
  font-size: 13px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 4px;
  width: 300px;
}

.search-box:focus {
  border-color: #888;
  outline: none;
}

.dropbtn {
  border-radius: 50%;
  border: none;
  cursor: pointer;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 100px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown-content a:hover {
  background-color: #f1f1f1
}

.dropdown:hover .dropdown-content {
  display: block;
}

.text-button {
  background: none;
  border: none;
  color: black;
  font-size: 14px;
  font-family: Arial, sans-serif;
  cursor: pointer;
  transition: color 0.3s, text-decoration 0.3s;
}

.text-button:hover {
  color: #00a0ff;
}
</style>
<script>
import request from "@/Utils/request.js";
import axios from "axios";
import {Delete, DocumentCopy, PictureFilled, Plus, Pointer, UploadFilled} from "@element-plus/icons-vue";
import UserMenu from "@/components/UserMenu.vue";
export default {
  components: {Delete, Plus, PictureFilled, UploadFilled, DocumentCopy, Pointer,UserMenu},
  data() {
    return {
      sicknameinput:'',
      EditMsgdialogVisible:false,
      ReserchInput:'',
      replysickname:'',
      PlsickName:[],
      id:'',
      inputComment:'说点什么...',
      likeRecord:[],
      commentNum:'',
      foreignid:'',
      textareaComment:'',
      dialogComment:false,
      response:'',
      fileList:[],
      disabled: false,
      message: [],
      commentmessage:[],
      textarea: '',
      dialogVisible: false,
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      likeStorage:localStorage.getItem("likeRecord")?JSON.parse(localStorage.getItem("likeRecord")):{},
    }
  },
  methods: {
    replyPl(id,sickname){
      this.id=id
      this.inputComment="回复:"+sickname
      this.replysickname=sickname
    },
    Delete(foreignid){
      request.delete(`/Community/deleteDtMsg/${foreignid}`).then(res=>{
        this.$message.success("操作成功")
        this.fetchData()
      })
    },
    comment(foreignid){
      request.get(`/Community/selectUserComment/${foreignid}`).then(res=>{
        this.commentmessage=res
      })
      request.get(`/Community/CommentCount/${foreignid}`).then(res=>{
        this.commentNum=res
      })
      // request.get(`/Community/getSickname/${foreignid}`).then(response=>{
      //   this.PlsickName=response
      //   this.PlsickName.forEach(item=>{
      //     console.log(item['sickname'])
      //   })
      // })
      this.foreignid=foreignid
      this.dialogComment=true
    },
    achieve(){
        request.put("/Community/updatesickname1",{
          sickname:this.sicknameinput,
          account:this.user.account
        })
       request.put("/Community/updatesickname2",{
          sickname:this.sicknameinput,
          account:this.user.account
        })
        request.put("/Community/updatesickname3",{
        sickname:this.sicknameinput,
        account:this.user.account
      })
      this.$message.success("修改成功")
      setTimeout(()=>{
        request.put("/Community/updatesickname4",{
        })
        location.reload()
      },2000)

      //修改localstorage
      let user=JSON.parse(localStorage.getItem('user'));
      user.sickname=this.sicknameinput
      localStorage.setItem('user',JSON.stringify(user))

    },
    edit(){
    this.EditMsgdialogVisible=true
    },
    sendComment(){
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整
      const day = String(now.getDate()).padStart(2, '0');
      const nowtime=`${year}-${month}-${day}`;
      if(this.textareaComment === ""){
        this.$message.error("评论为空")
      }else if(this.inputComment === '说点什么...'){
        request.post("/Community/insertPlMsg",{
          foreignid:this.foreignid,
          sickname:this.user.sickname,
          image:this.user.image,
          replycontent:this.textareaComment,
          replytime:nowtime,
          account:this.user.account
        }).then(res=>{
        })
        this.dialogComment = false;
        this.$message.success("评论成功")
        // this.comment(this.foreignid)
        location.reload()
      }else {
        request.post('/Community/ReplyComment',{
          foreignid:this.foreignid,
          sickname:this.user.sickname,
          image:this.user.image,
          replycontent:this.textareaComment,
          replytime:nowtime,
          pid:this.id,
          replysickname:this.replysickname,
          account:this.user.account
        }).then(res=>{
          this.$message.success("回复成功")
          location.reload()
        })
      }
    },
    searchData(ReserchInput){
      request.get(`/Community/getUserByContentLike/${ReserchInput}`).then(res=>{
        console.log("------------")
        console.log(res)
        this.message=res
      })
    },
    fetchData(){
      request.get('/Community/selectAllbysickname',{
        params:{
          sickname:this.user.sickname
        }
      }).then(res => {
        console.log(res)
        this.message = res
      })
    },
    giveLike(foreignid){
      let likeRecord = localStorage.getItem("likeRecord");
      this.likeStorage = likeRecord ? JSON.parse(likeRecord) : {};  // 解析存储的数据，如果没有则初始化为空对象

      const updateLikeStatus = (foreignid, isLiked) => {
        // 更新点赞状态
        if (!this.likeStorage[foreignid]) {
          this.likeStorage[foreignid] = {};
        }
        // 如果是点赞，设置为 true；如果是取消点赞，设置为 false
        this.likeStorage[foreignid][this.user.sickname] = isLiked;

        localStorage.setItem("likeRecord", JSON.stringify(this.likeStorage));
      };

      const updateLikenum = (foreignid, isLiked) => {
        const url = isLiked ? `/Community/addLikenum/${foreignid}` : `/Community/minusLikenum/${foreignid}`;

        // 发送请求，更新服务器端的点赞数
        request.put(url).then(res => {
          this.fetchData();  // 数据更新后重新请求
        }).catch(error => {
          console.error("点赞操作失败", error);
        });
      };
      if (this.likeStorage[foreignid] && this.likeStorage[foreignid][this.user.sickname]) {
        // 用户已经点赞，进行取消点赞
        updateLikeStatus(foreignid, false);  // 取消点赞
        updateLikenum(foreignid, false);     // 发送取消点赞请求
      } else {
        // 用户没有点赞，进行点赞
        updateLikeStatus(foreignid, true);   // 点赞
        updateLikenum(foreignid, true);      // 发送点赞请求
      }
    },
    handleSuccess(response,file,fileList){
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，+1调整
      const day = String(now.getDate()).padStart(2, '0');
      const nowtime=`${year}-${month}-${day}`;
      request.post('/Community/insertDtMsg',{
        account:this.user.account,
        sickname:this.user.sickname,
        content:this.textarea,
        image:this.user.image,
        commentimage:response,
        posttime:nowtime
      }).then(res=>{
        console.log("this.response=>",this.response)
      })
      this.dialogVisible = false
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid);
    },
    send() {
      if (this.textarea === '') {
        this.$message.error("内容不能为空")
      }else {
        this.$refs.upload.submit();
        this.$message.success("发布成功！")
        setTimeout(()=>{
          location.reload()
        },2000)
      }
    },
    publish() {
      this.dialogVisible = true
    },
    search(ReserchInput) {
      if(this.ReserchInput === ""){
        location.reload()
      }else {
        this.searchData(ReserchInput)
      }

    },
    cancel() {
      localStorage.removeItem("user");
      localStorage.removeItem("usermsg");
      localStorage.removeItem("employeemsg");
      this.$router.push('/login');
      this.$message({
        message: '退出成功!',
        type: 'success'
      })
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        var imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    getFile(file, fileList) {
      this.getBase64(file.raw).then(res => {
        const params = res.split(',')
        console.log(params, 'params')
        if (params.length > 0) {
          this.proofImage = params[1]
        }
        this.imgResult1 = params[0] + ',' + params[1]
      })
    },
  },
  mounted() {
    this.fetchData();
    this.giveLike();
    this.sicknameinput=this.user.sickname
  }

}
</script>